package cn.monkey.chat.server.connect.chat.filter;

import cn.monkey.chat.server.connect.chat.ChatExchange;
import cn.monkey.chat.server.connect.chat.data.ClientExchangePkgPair;
import cn.monkey.chat.server.proto.Message;
import cn.monkey.chat.server.proto.Package;
import cn.monkey.chat.server.proto.User;
import cn.monkey.io.transport.core.server.FilterChain;
import cn.monkey.state.scheduler.SchedulerManager;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class LastChatMessageFilter implements ChatMessageFilter {

    private final Logger log = LoggerFactory.getLogger(LastChatMessageFilter.class);

    private final SchedulerManager schedulerManager;

    public LastChatMessageFilter(SchedulerManager schedulerManager) {
        this.schedulerManager = schedulerManager;
    }

    // 私聊的groupId
    String newPrivateChatGroupId(ChatExchange exchange, User to) {
        String from = exchange.id();
        String toUid = to.getUid();
        return from.compareTo(toUid) > 0 ? toUid + from : from + toUid;
    }

    @Override
    public void doFilter(ChatExchange exchange, Package s, FilterChain<ChatExchange, Package> filterChain) {
        String groupId = s.getGroupId();
        if (!Strings.isEmpty(groupId)) {
            schedulerManager.addEvent(groupId, new ClientExchangePkgPair(exchange, s));
            return;
        }
        // 私聊
        Object data = s.getData();
        if (data instanceof Message message) {
            List<User> messageTo = message.getTo();
            if (messageTo == null || messageTo.size() != 1) {
                log.error("invalid private chat pkg: {}", s);
                return;
            }
            groupId = this.newPrivateChatGroupId(exchange, messageTo.getFirst());
            schedulerManager.addEvent(groupId, new ClientExchangePkgPair(exchange, s));
            return;
        }
        log.error("invalid chat pkg: {}", s);
    }
}


